import uuid
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from api.extension.mixins import OpsCreateModelMixin
from api.serializers.account import RegisterSerializer, AuthSerializer
from rest_framework.response import Response
from api.extension import return_code
from api.models import UserInfo
from django.db.models import Q
from api.extension.throttle import CloudCreateThrottle


class RegisterView(OpsCreateModelMixin, GenericViewSet):
    """
     1. 注册只需提供POST
     2. 请求进来执行 DigCreateModelMixin的create方法
     3. 获取数据request.data，进行校验（RegisterSerializer）
     """
    permission_classes = []
    authentication_classes = []
    serializer_class = RegisterSerializer
    throttle_objects = [CloudCreateThrottle(), ]

    def perform_create(self, serializer):
        serializer.validated_data.pop("confirm_password")
        serializer.save()
        for throttle in self.get_throttles():
            throttle.done()


class AuthView(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_objects = []

    def post(self, request):
        # 1. 获取用户请求 & 验证用户
        serializer = AuthSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({"code": return_code.VALIDATE_ERROR, "detail": serializer.errors})
        # 2. 验证通过，从验证通过后的数据中获取需要的数据
        username = serializer.validated_data.get("username")
        password = serializer.validated_data.get("password")
        phone = serializer.validated_data.get("phone")
        # 从数据库中查询数据
        user_object = UserInfo.objects.filter(Q(Q(username=username) | Q(phone=phone)), password=password).first()
        if not user_object:
            return Response({"code": return_code.VALIDATE_ERROR, "error": "用户名或密码错误"})
        # 验证通过并且有用户数据，创建token 并返回token
        token = str(uuid.uuid4())
        user_object.token = token
        user_object.save()
        # for throttle in self.get_throttles():
        #     throttle.done()
        return Response({"code": return_code.SUCCESS, "data": {"token": token, "name": user_object.username}})
